package com.definity.toolkit.web.controller;

import java.io.File;

import br.com.caelum.vraptor.interceptor.download.ByteArrayDownload;
import br.com.caelum.vraptor.interceptor.download.Download;
import br.com.caelum.vraptor.interceptor.download.FileDownload;

import com.definity.toolkit.storage.FileData;
import com.definity.toolkit.storage.StorageData;
import com.definity.toolkit.storage.StorageService;
import com.definity.toolkit.web.util.HttpUtils;

public abstract class AbstractStorageController<T extends StorageData, C> {
	
	public AbstractStorageController() {

	}
	
	public Download get(Long fileId) {
		T data = getService().get(fileId);

		return getDownloadType(data);
	}

	protected Download getDownloadType(T data) {
		C content = getService().getContent(data);

		if (data instanceof FileData) {
			FileData fileData = (FileData) data;
			if (fileData.getPath().startsWith("http")) {
				try {
					byte[] buffer = HttpUtils.get(fileData.getPath());
					return new ByteArrayDownload(buffer, data.getContentType(), data.getName());
				} catch (Exception e) {
					return null;
				}
			}
			return new FileDownload((File) content, data.getContentType());
		}
		if (content instanceof File)
			return new FileDownload((File) content, data.getContentType());
		if (content instanceof byte[])
			return new ByteArrayDownload((byte[]) content, data.getContentType(), data.getName());
		
		return null;
	}

	protected abstract StorageService<T, C> getService();
	
}
